package base64_captcha

import (
	"context"
	"time"

	"gitee.com/huangxinbo/xcas/pkg/logger"
	"github.com/redis/go-redis/v9"
)

// RedisStore Redis storage implementation
type RedisStore struct {
	client *redis.Client
	logger *logger.Logger
	prefix string
	ctx    context.Context
}

// NewRedisStore creates Redis storage instance
func NewRedisStore(client *redis.Client, logger *logger.Logger) *RedisStore {
	return &RedisStore{
		client: client,
		logger: logger,
		prefix: "captcha:",
		ctx:    context.Background(),
	}
}

// Set sets captcha
func (r *RedisStore) Set(id string, value string) error {
	key := r.prefix + id
	// Set captcha expiration time to 5 minutes
	err := r.client.Set(r.ctx, key, value, 5*time.Minute).Err()
	if err != nil {
		r.logger.Error("Redis set captcha failed: " + err.Error())
		return err
	}
	r.logger.Info("Redis set captcha successful, ID: " + id)
	return nil
}

// Get gets captcha
func (r *RedisStore) Get(id string, clear bool) string {
	key := r.prefix + id
	value, err := r.client.Get(r.ctx, key).Result()
	if err != nil {
		if err != redis.Nil {
			r.logger.Error("Redis get captcha failed: " + err.Error())
		}
		return ""
	}

	if clear {
		// Delete captcha after verification
		err = r.client.Del(r.ctx, key).Err()
		if err != nil {
			r.logger.Error("Redis delete captcha failed: " + err.Error())
		} else {
			r.logger.Info("Redis delete captcha successful, ID: " + id)
		}
	}

	return value
}

// Verify verifies captcha
func (r *RedisStore) Verify(id, answer string, clear bool) bool {
	storedValue := r.Get(id, clear)
	return storedValue == answer
}
